<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 目录树 -->
      <el-col :lg="4" :md="5" :sm="6" :xs="24" class="mb-[12px] !pr-0">
        <user-organization-tree
          ref="organizationTree"
          v-model="searchParam.departmentId"
          @node-click="search"
        />
      </el-col>
      <el-col :lg="20" :md="19" :sm="18" :xs="24">
        <!-- 搜索框 -->
        <div class="search-container">
          <el-form :model="searchParam" :inline="true">
            <el-form-item label="员工号">
              <el-input
                v-model="searchParam.empNo"
                placeholder="请输入员工号"
                clearable
                @keyup.enter="search"
              />
            </el-form-item>
            <el-form-item label="登录名称">
              <el-input
                v-model="searchParam.loginName"
                placeholder="请输入登录名称"
                clearable
                @keyup.enter="search"
              />
            </el-form-item>
            <el-form-item label="用户姓名">
              <el-input
                v-model="searchParam.firstName"
                placeholder="请输入用户姓名"
                clearable
                @keyup.enter="search"
              />
            </el-form-item>
            <el-form-item label="是否启用">
              <el-select
                v-model="searchParam.enabled"
                placeholder="请选择是否启用"
                clearable
              >
                <el-option
                  v-for="item in enabledList"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="部门">
              <SelectOriganization
                :isCheckStrictly="true"
                :isMultiple="false"
                :disabled="true"
                :selectData="searchParam.departmentId"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">
                <i-ep-search />
                搜索
              </el-button>
              <el-button @click="reset">
                <i-ep-refresh />
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- 列表 -->
        <el-card shadow="never" class="table-container">
          <template
            #header
            v-if="authAllPerm(['sys:user:add', 'sys:user:delete'])"
          >
            <el-button
              v-hasPerm="['sys:user:add']"
              type="success"
              plain
              @click="openDialog()"
            >
              <i-ep-plus />
              新增
            </el-button>
            <el-button
              v-hasPerm="['sys:user:delete']"
              type="danger"
              plain
              :disabled="ids.length === 0"
              :loading="deleteLoading"
              @click="handleTableDelete()"
            >
              <i-ep-delete />
              删除
            </el-button>
            <el-button type="primary" @click="userImport">导入 </el-button>
            <el-button
              @click="
                useDownload(
                  '/system/sysUser/exportTemp',
                  '用户数据上传模板',
                  searchParam
                )
              "
            >
              导入模板下载
            </el-button>
          </template>

          <el-table
            ref="dataTableRef"
            :data="tableData"
            v-loading="loading"
            highlight-current-row
            border
            @selection-change="handleSelectionChange"
            @sort-change="onTableSortChanged"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              :prop="item.prop"
              :label="item.label"
              v-for="item in tableHeader"
              :key="item.prop"
              :sortable="item?.sort"
              :width="item.width"
              :align="item.align"
              show-overflow-tooltip
            >
              <template v-if="item.prop === 'enabled'" #default="scope">
                <el-tag v-if="scope.row.enabled === 1" type="success"
                  >启用</el-tag
                >
                <el-tag v-else type="info">停用</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="380"
              align="center"
              v-if="
                authAllPerm([
                  'sys:user:role',
                  'sys:user:organize',
                  'sys:user:reset',
                  'sys:user:edit',
                  'sys:user:delete',
                ])
              "
            >
              <template #default="scope">
                <el-button
                  v-hasPerm="['sys:user:role']"
                  type="success"
                  size="small"
                  link
                  @click="openRoleDialog(scope.row)"
                >
                  <i-ep-user />
                  角色
                </el-button>
                <el-button
                  v-hasPerm="['sys:user:organize']"
                  type="warning"
                  size="small"
                  link
                  @click="openOrganDialog(scope.row)"
                >
                  <i-ep-connection />
                  组织机构
                </el-button>
                <el-button
                  v-hasPerm="['sys:user:reset']"
                  size="small"
                  link
                  @click="openResetPsw(scope.row)"
                >
                  <i-ep-setting />
                  重置密码
                </el-button>
                <el-button
                  v-hasPerm="['sys:user:edit']"
                  type="primary"
                  size="small"
                  link
                  @click="openDialog(scope.row)"
                >
                  <i-ep-edit />
                  编辑
                </el-button>
                <el-button
                  v-hasPerm="['sys:user:delete']"
                  type="primary"
                  size="small"
                  link
                  @click="handleTableDelete(scope.row.id)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            :background="true"
            :current-page="pageable.pageNum"
            :page-size="pageable.pageSize"
            :page-sizes="[10, 25, 50, 100]"
            :total="pageable.total"
            layout="total, sizes, prev, pager, next, jumper"
            class="mt-[20px]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-col>
    </el-row>
    <!-- 新增 -->
    <add-user
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id: string) => (id?.length ? getTableList() : getTableList())"
      @get-enabled-list="getEnabledList"
      @change-visible="changeVisible"
    />
    <!-- :organizationList="organizationTree.deptList" -->
    <!-- 重置密码 -->
    <ResetPsw
      v-model:visible="resetVisible"
      v-model:id="resetId"
      v-model:name="resetName"
    />
    <!-- 组织机构 -->
    <up-user-organization
      :visible="organDialog.visible"
      :title="organDialog.title"
      :data="organDialog.data"
      :id="organDialog.id"
      @reset-table="getTableList"
      @change-visible="changeVisibleOrgan"
    />
    <!-- 角色 -->
    <up-user-role
      :visible="roleDialog.visible"
      :title="roleDialog.title"
      :data="roleDialog.data"
      :id="roleDialog.id"
      @reset-table="getTableList"
      @change-visible="changeVisibleRole"
    />
    <!--导入-->
    <ImportExcel ref="importRef" />
  </div>
</template>

<script setup lang="ts">
import { filterOrder } from "@/utils/commonHooks";
import { useDownload, useTable } from "@/utils/useTable";
import request from "@/utils/request";
import { authAllPerm } from "@/utils/index";

defineOptions({
  name: "SYSTEMUSER",
  inheritAttrs: false,
});

const organizationTree = ref();

// 请求参数
const requestApi = "/system/sysUser/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  loginName: "",
  firstName: "",
  enabled: null,
  empNo: "",
  departmentId: "",
};

const deleteParam = {
  api: "/system/sysUser/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

// 数据请求错误后处理
// function dataCallBack() {}   //需要处理
const dataCallBack = ref(undefined); //无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  loading,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  deleteLoading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  // getOrganizations();
  // getRoleList();
});

const tableHeader = [
  {
    prop: "empNo",
    label: "员工号",
    sort: true,
  },
  {
    prop: "loginName",
    label: "登录名称",
  },
  {
    prop: "firstName",
    label: "用户姓名",
  },
  {
    prop: "departmentName",
    label: "部门",
  },
  {
    prop: "mobile",
    label: "手机号",
  },
  {
    prop: "createTime",
    label: "注册日期",
    sort: true,
    width: 160,
    align: "center",
  },
  {
    prop: "enabled",
    label: "是否启用",
    align: "center",
    width: 100,
  },
];

// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });

/** 回显是否开启list */
const enabledList: any = ref([]);
function getEnabledList(list: []) {
  enabledList.value = list;
}

/** 打开角色表单弹窗 */
const addDialog = reactive<DialogOption>({
  visible: false,
  title: "",
  data: {},
});

async function getSystemUser(id: string) {
  const { data } = await request({
    url: `/system/sysUser/get/${id}`,
    method: "get",
  });
  addDialog.data = data;
}

function openDialog(roleObj?: any) {
  addDialog.visible = true;
  if (roleObj) {
    addDialog.title = `编辑用户【${roleObj.firstName}】`;
    getSystemUser(roleObj.id);
  } else {
    addDialog.data = {};
    addDialog.title = "新增用户";
  }
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
}

/** 打开组织机构弹窗 */
const organDialog = reactive<DialogOption>({
  visible: false,
  title: "",
  id: "",
  data: [],
});

const selectOrganList: any = ref([]);
async function openOrganDialog(roleObj?: any) {
  selectOrganList.value = await getOrganizations();
  organDialog.visible = true;
  organDialog.title = `组织机构【${roleObj.firstName}】`;
  organDialog.data = selectOrganList.value;
  organDialog.id = roleObj.id;
}

function changeVisibleOrgan(value: boolean) {
  organDialog.visible = value;
}

async function getOrganizations() {
  return new Promise<void>(async (resolve, reject) => {
    try {
      const { data } = await request({
        url: "/system/sysOrganization/getUsableTree",
        method: "post",
        data: {},
      });
      resolve(data);
    } catch (e) {
      reject(e);
    }
  });
}

/**
 * 修改密码 呼出弹窗
 */
interface ResetPswData {
  id: string;
  loginName: string;
}
const resetVisible = ref(false);
const resetId = ref("");
const resetName = ref("");
function openResetPsw({ id, loginName }: ResetPswData) {
  resetVisible.value = true;
  resetId.value = id;
  resetName.value = loginName;
}

/** 打开角色分配弹窗 */
const roleDialog = reactive<DialogOption>({
  visible: false,
  title: "",
  id: "",
  data: [],
});

async function openRoleDialog(roleObj?: any) {
  getRoleList().then((data) => {
    roleDialog.visible = true;
    roleDialog.title = `角色分配【${roleObj.firstName}】`;
    roleDialog.data = data;
    roleDialog.id = roleObj.id;
  });
}

function changeVisibleRole(value: boolean) {
  roleDialog.visible = value;
}

async function getRoleList() {
  return new Promise<void>(async (resolve, reject) => {
    try {
      const { data } = await request({
        url: "/system/sysRole/listALL",
        method: "post",
        data: {},
      });
      resolve(data);
    } catch (e) {
      reject(e);
    }
  });

  // const { data } = await request({
  //   url: "/system/sysRole/listALL",
  //   method: "post",
  //   data: {},
  // }).finally(() => {});
  // selectRoleList.value = data;
}
// 导入计划
const importRef = ref();
const uploadApi = "/system/sysUser/upload";
async function userImportApiFunc(formdata: FormData, config: any) {
  await request
    .post(uploadApi, formdata, config)
    .then((res: any) => {
      importRef.value.resCode = 0;
      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: "上传成功！",
        });
      }
    })
    .catch((e) => {
      importRef.value.resCode = 500;
    });
}
const userImport = () => {
  let params = {
    title: "导入用户数据",
    tempApi: "", //模板下载
    importApi: userImportApiFunc, // 导入
    getTableList: getTableList, // 成功后回调
    isShowTemp: false,
    otherParams: {},
  };
  importRef.value.acceptParams(params);
};
</script>
<style lang="scss" scoped>
:deep(.el-form .el-form-item__label) {
  width: 63px;
}
</style>
